import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table } from 'antd';
/**
 * 单元格合并处理
 * @param text 当前单元格的值
 * @param data 当前分页所有数据
 * @param key 当前列的dataIndex
 * @param index 当前数据所在下标
 * @returns {number} 待合并单元格数量
 */
const mergeCells = (text, data, key, index) => {
  // 上一行该列数据是否一样
  if (index !== 0 && text === data[index - 1][key]) {
    return 0;
  }
  let rowSpan = 1;
  // 判断下一行是否相等
  for (let i = index + 1; i < data.length; i += 1) {
    if (text !== data[i][key]) {
      break;
    }
    rowSpan += 1;
  }
  return rowSpan;
};

export default () => {
  const list = [
    {
      id: '1',
      group: '组一',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组一',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组二',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组二',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组三',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组四',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组五',
      age: 32,
      age1: 8,
      user: '用户1',
      select: true,
    },
    {
      id: '1',
      group: '组五',
      age: 32,
      age1: 32,
      user: '用户1',
      select: true,
    },
  ];

  const columns = [
    {
      title: 'group',
      dataIndex: 'group',
      key: 'group',
      render: (text, record, index) => {
        const obj = {
          children: text !== null ? text : '',
          props: {},
        };
        obj.props.rowSpan = mergeCells(text, 'group', index);
        return obj;
      },
    },
    {
      title: '用户',
      dataIndex: 'user',
      key: 'user',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '年龄',
      dataIndex: 'age1',
      key: 'age1',
    },
    {
      title: '住址',
      dataIndex: 'address',
      key: 'address',
    },
  ];
  const sums = 0;
  const dataSource = list && list.length > 0 ? [...list, sums] : [];

  return (
    <PageContainer>
      <Card title="Default size card">
        <Table dataSource={dataSource} columns={columns} rowKey={(record) => record.id} bordered />
      </Card>
    </PageContainer>
  );
};
